package software.literature.config;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class ConfigureManager {
private static String databasesFile="config.ini";
private static String currentDatabase="current.ini";
private static ConfigureManager configData;

private ConfigureManager(){
		
}

public static ConfigureManager getInstance(){
	if(null==configData){
		configData=new ConfigureManager();
	}
	return configData;
	
}
public String getConfigFile() {
	return databasesFile;
}

public void setConfigFile(String configFile) {
	this.databasesFile = configFile;
}
/**
 * 
 * @param selected
 * @return
 */
public int updateDataBase(ArrayList<String> databases) {
	// TODO Auto-generated method stub
//	if(!databases.contains(selected)){
		try {
			File file=new File(databasesFile);
			file.createNewFile();
			FileWriter fw=new FileWriter(databasesFile,false);
			int le=databases.size();
			for(int i=0;i<le;i++){
				fw.write(databases.get(i));
				fw.write("\n");
			}
			fw.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return -1;
		}	
		return 1;
}
public boolean updateCurrentDB(String currentDB){
	try {
		FileWriter fw=new FileWriter(currentDatabase,false);
		fw.write(currentDB);
		fw.close();
		return true;
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	return false;	
	
}
public ArrayList<String> getDataBases() {
	ArrayList<String>  databases=new ArrayList<String>();
	try {
		File file=new File(databasesFile);
		file.createNewFile();
		BufferedReader read=new BufferedReader(new FileReader(databasesFile));
	    String s="";
	    while(null!=(s=read.readLine())){
		   if(s.trim().equals("")){
			   
		   }else{
			   File f=new File(s);
			   if(f.canWrite()){//only if the database file can write
				   databases.add(s.trim());  
			   }
		   }
		   
	   }
	   read.close();
	}catch(Exception e){
		e.printStackTrace();
	}
	return databases;
}

public static String getCurrentLocation() {
	return databasesFile;
	// TODO Auto-generated method stub
}
public String getCurrentDB() {
	 try{  File file=new File(currentDatabase);
	   file.createNewFile();
	   BufferedReader read=new BufferedReader(new FileReader(file));
	   String  currentDB=read.readLine();
	   if(null != currentDB){
		   currentDB=currentDB.trim(); 
	   }else{
		   currentDB="";
	   }
	   read.close();
	   return currentDB;
	} catch (FileNotFoundException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	 return "";
}

}
